#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.basic.component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 修改Request中的参数
 *
 * @author wupanhua
 * @date 2021-04-10 11:53
 *
 * <pre>
 *              ${copyright}
 *      Copyright (c) 2019. All Rights Reserved.
 * </pre>
 */
public class RequestParameterWrapper extends HttpServletRequestWrapper {

	private Map<String, String[]> params = new HashMap<>();

	/**
	 * Description:
	 * <>
	 *
	 * @param request     1
	 * @param extraParams 2
	 * @author wenxiaopeng
	 * @date 12:45 2021/04/10
	 **/
	public RequestParameterWrapper(HttpServletRequest request, Map<String, String[]> extraParams) {
		this(request);
		addParameters(extraParams);
	}

	public RequestParameterWrapper(HttpServletRequest request) {
		super(request);
		this.params.putAll(request.getParameterMap());
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		return params;
	}

	/**
	 * Description:
	 * <添加额外参数>
	 *
	 * @param extraParams 1
	 * @return void
	 * @author wenxiaopeng
	 * @date 12:45 2021/04/10
	 **/
	public final void addParameters(Map<String, String[]> extraParams) {
		for (Map.Entry<String, String[]> entry : extraParams.entrySet()) {
			addParameter(entry.getKey(), entry.getValue());
		}
	}

	/**
	 * 重写getParameter，代表参数从当前类中的map获取
	 *
	 * @param name
	 * @return
	 */
	@Override
	public String getParameter(String name) {
		String[] values = params.get(name);
		if (values == null || values.length == 0) {
			return null;
		}
		return values[0];
	}

	/**
	 * 同上
	 *
	 * @param name
	 * @return
	 */
	@Override
	public String[] getParameterValues(String name) {
		return params.get(name);
	}

	/**
	 * Description:
	 * <添加参数>
	 *
	 * @param name  1
	 * @param value 2
	 * @author wenxiaopeng
	 * @date 12:46 2021/04/10
	 **/
	public void addParameter(String name, Object value) {
		if (value != null) {
			if (value instanceof String[]) {
				params.put(name, (String[]) value);
			} else if (value instanceof String) {
				params.put(name, new String[]{(String) value});
			} else {
				params.put(name, new String[]{String.valueOf(value)});
			}
		}
	}
}
